define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, NewnoticeDetail, $ionicSlideBoxDelegate, GoPage, GoDialog, GoShare,GoWapAuth, $window, $timeout, $stateParams, $ionicModal, Auth, $interval, $ionicPopup,$sce) {
		
		$scope.input = new Object();
		$scope.isshow = true;
		
		//画面加载
		$scope.$on('$ionicView.afterEnter', function() {
			$scope.set_time = false;
			$scope.goods_id = $stateParams.goods_id;
			$scope.product_id = $stateParams.product_id;
			$scope.act_id = $stateParams.act_id;
			$scope.init_data();
		}, false);
		
		$scope.$on('$ionicView.afterLeave', function() {
			$scope.closeGuidShare();
		}, false);
		
		$scope.$on('$ionicView.beforeLeave',function(){
			if($scope.timer){
				$interval.cancel($scope.timer);
			}
		})
		
		//初始化页面
		$scope.init_data = function() {
			NewnoticeDetail.product_detail($scope.act_id,$scope.goods_id, $scope.product_id, function(data) {
				if(!data.success){
					GoDialog.alert("提示",data.msg,function(){
						GoPage.go_back();
					})
					return;
				}
				console.log(data.result)
				if(data.result) {
					$scope.input.goods_num = 1;
					if(data.result.min_buy != null && data.result.min_buy != '0'){//默认购买数量
						$scope.input.goods_num = parseInt(data.result.min_buy);
					}
					$scope.minBuyNum = $scope.input.goods_num;//最小购买数，这里被当做了购买基数，不知为何
					$scope.datas = data.result;
					$scope.detail = data.result.goods
					$scope.init_time(data.result, data.process_time);
					var video_url = data.result.goods.video_code;
					if(video_url) {//如果有视频，优先显示视频
						$scope.myURL = $sce.trustAsResourceUrl($scope.getIsThird(video_url));
						$timeout(function() {//视频播放不了提示用户
							var iframeVideo = document.getElementById('iframeVideo')
							if(iframeVideo != null) {
								if(iframeVideo.contentWindow.document) {
									var video = iframeVideo.contentWindow.document.body;
									var div = document.createElement("div");
									if(video_url)
										div.innerText = '视频无法播放(链接不是通用链接)';
									else
										div.innerText = '视频未设置播放链接';
									div.setAttribute('style', 'text-align: center;margin-top: -1rem;color: rgb(207, 51, 52);')
									video.appendChild(div);
								}
							}
						}, 2000)
					} else{//普通轮播图
						$ionicSlideBoxDelegate.$getByHandle('advs-handle').update(); //解决无法加载
						$ionicSlideBoxDelegate.$getByHandle('advs-handle').loop(true); //循环
					}
					$scope.go_share_wx();
				}
			});
		}
		
		//判断是否含有iframe标签的，如果是，则获取其中的url。
		$scope.getIsThird = function(url) {
			//iframe模式。如：<iframe frameborder="0" width="640" height="498" src="https://v.qq.com/iframe/player.html?vid=f0626cirzn4&tiny=0&auto=0" allowfullscreen></iframe>
			if(url.lastIndexOf('<iframe') == 0 && url.lastIndexOf('</iframe>') > 0) {//获取iframe里的url
				var video = document.createElement("div");
				video.innerHTML = url;
				var ifreame = video.childNodes[0];
				return ifreame.getAttribute("src");//转换为dom，再iframe的src
			}else{
				return url;
			}
		};
		
		
		//商品数量+1
		$scope.goods_add = function() {
			if($scope.detail.max_count != undefined)
				var max_count = $scope.detail.max_count > $scope.detail.store ? $scope.detail.store : $scope.detail.max_count;
			else
				var max_count = $scope.detail.store;
			if($scope.input.goods_num>=$scope.detail.store||$scope.input.goods_num >= max_count) {
				GoDialog.alert("提示","最多只能购买"+max_count+"件");
				return;
			}
			$scope.input.goods_num += parseInt($scope.minBuyNum);
		};
		
		//商品数量-1
		$scope.goods_reduce = function() {
			if($scope.input.goods_num > 1)
				$scope.input.goods_num -= parseInt($scope.minBuyNum);
		};
		
		/************提交表单***************/
		$scope.submit = function() {
			if($scope.detail.store<1) {
				GoDialog.alert("提示","对不起，该商品没有库存了！");
				return;
			}
			if(!$scope.input.goods_num) {
				GoDialog.toast("请填写购买数量");
				return;
			}
			NewnoticeDetail.buy($scope.detail.goods_id, $scope.product_id, $scope.input.goods_num, $scope.act_id, function(data) {
				if(data.success)
					GoPage.go_states("afsrue", {
						"type": "newnotice",
						"status": 'fastbuy'
					});
				else {
					GoDialog.alert("提示",data.msg);
//					$scope.init_data();
				}
			})
		}
		/************提交表单***************/
		
		$scope.init_time = function(data, now_time) {
			if(now_time < data.start_time) {
				$scope.isshow = false;
				$scope.btn_name = '未开始';
				$scope.act_time_name = '距开始';
				if(data.now_time != undefined)
					data.now_time = data.now_time - 1;
				else
					data.now_time = data.start_time - now_time;
			} else {
				$scope.act_time_name = '距结束';
				if($scope.detail.store <= 0) {
					$scope.btn_name = '已售完';
					$scope.isshow = false;
				}
				if(data.now_time != undefined)
					data.now_time = data.now_time - 1;
				else
					data.now_time = data.end_time - now_time;
			}
			data.formate_time = $scope.formate_time(data.now_time);
			$scope.set_timer(now_time);
		};
		$scope.set_timer = function(now_time) {
			if(!$scope.set_time){
				$scope.set_time = true;
			}else{
				return;
			}
			$interval(function() {
				if($scope.datas.now_time != undefined) {
					$scope.datas.now_time = $scope.datas.now_time - 1;
					if($scope.datas.now_time <= 0) {
						if(now_time >= $scope.datas.start_time) {
							$scope.datas.now_time = $scope.datas.end_time - now_time;
							$scope.act_time_name = '距结束';
						} else {
							$scope.datas.now_time = $scope.datas.start_time - now_time;
							$scope.act_time_name = '距开始';
							if($scope.detail.store <= 0) {
								$scope.btn_name = '已售完';
								$scope.isshow = false;
							} else {
								$scope.isshow = true;
							}
						}
					}
				} else {
					if(now_time > $scope.datas.start_time) {
						$scope.datas.now_time = $scope.datas.end_time - now_time;
						$scope.act_time_name = '距结束';
					} else {
						$scope.datas.now_time = $scope.datas.start_time - now_time;
						$scope.act_time_name = '距开始';
						if($scope.detail.store <= 0) {
							$scope.btn_name = '已售完';
							$scope.isshow = false;
						} else {
							$scope.isshow = true;
						}
					}
				}
				now_time++;
				$scope.datas.formate_time = $scope.formate_time($scope.datas.now_time);
			}, 1000)
		};
		
		//计算时间
		$scope.formate_time = function(time) {
			var timeArr = [0,0,0,0];
			if(time > 0) {
				var day = parseInt(time / (3600 * 24));
				var hour = parseInt((time % (3600 * 24)) / 3600);
				if(hour < 10)
					hour = "0" + hour;
				var min = parseInt((time % 3600) / 60);
				if(min < 10)
					min = "0" + min;
				var second = time % 60;
				if(second < 10)
					second = "0" + second;
//				return day + '天' + hour + '小时' + min + '分' + second + '秒';
				timeArr[0] = day;
				timeArr[1] = hour;
				timeArr[2] = min;
				timeArr[3] = second;
			} else {
				$scope.isshow = false;
				$scope.btn_name = '已结束';
//				return '0天0小时0分0秒';
			}
			return timeArr;
		};
		
		//跳转到首页
		$scope.onshow_first = function() {
			GoPage.go_states("first", {"store_id": $scope.detail.store_id});
		};
		
		
		//跳转到商品详情
		$scope.onshow_productInfo = function() {
			GoPage.go_states("activity_info", {
				"goods_id": $scope.goods_id,
				"act_id": $scope.act_id,
				"product_id": $scope.product_id,
				"type":6
			});
		}
		
		//上拉跳转到商品详情
		$scope.isLoad = false;
		$scope.doRefreshMore = function(){
			$scope.isLoad = true;
			$scope.$broadcast('scroll.infiniteScrollComplete');
			$timeout(function() {
				$scope.isLoad = false;
			}, 3000);
			$scope.onshow_productInfo();
		}
		
		
		/***********显示《客服》**********/
		$ionicModal.fromTemplateUrl("templates/modal/customer_service.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_customer = modal;
		});
		//打开
		$scope.openModal_customer = function() {//客服
			NewnoticeDetail.contact_show($scope.detail.store_id, function(data) {
				if(!data||data.cusphone.length<1){
					GoDialog.alert("提示","店家暂时还没有设置客服哦");
					return;
				}
				$scope.customerList = data;
				$scope.modal_customer.show();
			})
		}
		//隐藏
		$scope.closeModal_customer = function() {
			$scope.modal_customer.hide();
		}
		//选择客服
		$scope.selectCustomer = function(index){
			$scope.customerList_index = index;
		}
		//联系客服
		$scope.do_tel = function() {
			$scope.closeModal_customer();
			if(!$scope.customerList_index) return;
			var param = $scope.customerList.cusphone[$scope.customerList_index];
			if(param.type == 2) {
				$window.location.href = "tel:" + param.value;
			} else if(param.type == 1) {
				if(param.isonline == '0') {
					GoPage.go_txcall3(param.id, param.code, param.vvckey);
				} else {
					GoPage.go_txcall2($scope.detail.store_id, $scope.detail.store_id, param.id, param.code, param.vvckey);
				}
			}
		}
		/***********显示《客服》**********/
		
		/***************活动规则**************/
		$ionicModal.fromTemplateUrl("templates/modal/activityRule.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_rule = modal;
		});
		//打开
		$scope.openModal_rule = function() {
			if(!$scope.detail.rule){
				$scope.detail.rule = $scope.datas.rule;
			}
			$scope.modal_rule.show();
		}
		//隐藏
		$scope.closeModal_rule = function() {
			$scope.modal_rule.hide();
		}
		/***************活动规则**************/
		
		/***************分享**************/
		$ionicModal.fromTemplateUrl("templates/modal/keyshare_modal.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_share = modal;
		});
		//打开
		$scope.openModal_share = function() {
			if($scope.openGuidShare()) {
				$scope.modal_share.show();
			}
		}
		//隐藏
		$scope.closeModal_share = function() {
			$scope.modal_share.hide();
		}
		
		//分享（自定义每个页面的参数）
		$scope.go_share = function(index) {
			var param = new Object();
			if($scope.detail) {
				param.title = $scope.detail.name ? $scope.detail.name : undefined;
				param.desc = $scope.detail.brief ? $scope.detail.brief : undefined;
				param.thumb = $scope.detail.title_images ? $scope.detail.title_images[0].image : undefined;
				param.link = 'newnotice_detail/'+$scope.act_id+'/' +$scope.goods_id+'/'+$scope.product_id;
			}
			GoShare.do_share(param, index);
		}
		
		//分享（自定义每个页面的参数）
		$scope.go_share_wx = function() {
			//分享打开
			GoWapAuth.execisoff(false);
			//设置分享
			var param = new Object();
			if($scope.detail) {
				param.title = $scope.detail.name ? $scope.detail.name : undefined;
				param.desc = $scope.detail.brief ? $scope.detail.brief : undefined;
				param.thumb = $scope.detail.title_images ? $scope.detail.title_images[0].image : undefined;
				param.link = 'activitythree/'+$scope.act_id+'/' +$scope.goods_id+'/'+$scope.product_id;
			}
			GoWapAuth.execshare(param);
		}
		/***************分享**************/
		
		
	}

	controller.$inject = ['$scope', 'NewnoticeDetail', '$ionicSlideBoxDelegate', 'GoPage', 'GoDialog', 'GoShare','GoWapAuth', '$window', '$timeout', '$stateParams', '$ionicModal', 'Auth', '$interval','$ionicPopup','$sce'];

	return app.registerController("newnotice_detailctrl", controller);
});